//登录接口
let jwt = require('jsonwebtoken')
let common = require('../controller/common')
let data = require('../controller/data')
let crypto = require('../controller/crypto')

module.exports = {
        async login (req,res) {
        let password = crypto.md5(req.body.password)
        email = req.body.email
        if(!email || !common.isEmail(email) ){
            res.json({
                status:501,
                message:'邮箱格式不正确！'
            })
           return false
    }
    if(!password){
        res.json({
            status:504,
            message:'请输入密码！'
        })
       return false
    }

    //验证邮箱和登录密码
    let isUser =await data.login([email,password])
    
    if(isUser){
      //获取token
      //sign（加密数据 加密密钥，token时间） 加密用户名
      let token = jwt.sign({email:email},'jwt',{
          expiresIn: 60*60*1
      })
      //第4步返回信息
      res.json({
          status:200,
          data:{
              token,
              info: { 
                  email: isUser.emial,
                  userid: isUser.userid,
                  status: isUser.status,
                  username: isUser.username
              },
              message:'OK'
          }
      })
  
    }else{
        res.json({
            status:511,
            message:'用户名或密码不正确'
        })
       return false
    }
  },
  verifyLogin (req,res){
      let token = req.body.token;
      //验证token
      jwt.verify(token,'jwt',function(err,result){
        //登录失效
        if(err){
            res.json({
                status:512,
                message:'登录失效'
            })
        }else{
            res.json({
                status:200,
                message:'ok!'
            })
        }
      })

  },
  //退出登录
  async loginout (req,res){

    //取数据库邮箱是否存在
    //返回状态
    //token
    let email = req.body.email;
   
    let isregister =await data.isRegister(email)
    
    if(!isregister){
        res.json({
            status:200,
            message:'ok'
        })
    }else{
        res.json({
            status:513,
            message:'用户登录已经超时？'
        })
    }
  }
}